<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总条数:{{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'aa'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top:10px">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
            <img :src="row.staffPhoto" alt="" srcset="" style="width:100px;height:100px">
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
          >
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div style="height: 60px; margin-top: 10px">
            <!-- 分页 -->
            <el-pagination
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :page-sizes="[2,5,10]"
              @current-change="hCurrentChange"
              @size-change="hSizeChange"
            />
          </div>
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <el-dialog :visible.sync="showDialog" @close="hCloseDialog">
        <empDialog
          ref="AddEmployee"
          @close="showDialog=false"
          @success="hsuccess"
        />
      </el-dialog>
      <!-- 分配角色弹层 -->
      // 使用组件
      <el-dialog :visible.sync="showDialogRole">
        <AssignRole v-if="showDialogRole" :roleid="curEmployeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// 引入组件

import AssignRole from './assignRole'
import EmployeeEnum from '@/constant/employees'
import { getEmployeeList, delEmployee } from '@/api/employee'
import empDialog from './empDialog'
// 将数组元素,转化为对象键值对
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false, // 控制角色的弹层
      showDialog: false, // 控制弹层
      list: [], // 渲染数组
      page: 1, // 当前页码
      size: 5, // 每页几条
      total: 0 // 总共数据条数
    }
  },
  created() {
    // 调用员工列表
    this.loadEmployeeList()
  },
  methods: {
    // 英文键转化为中文
    dataFormate(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const newlist = list[0]
      if (newlist) {
        const theader = Object.keys(newlist).map(item => {
          return mapInfo[item]
        })
        const data = list.map(item => {
          return Object.values(item)
        })
        return { theader, data }
      }
    },
    // 导出excel功能
    async handleDownload() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const res = await getEmployeeList(this.page, this.size)
        console.log('导出的res', res)
        if (res.code !== 10000) return
        // 2.格式化数据 header data
        const { theader, data } = this.dataFormate(res.data.rows)
        excel.export_json_to_excel({
          header: theader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 删除功能
    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(async() => {
        const res = await delEmployee(id)
        console.log('要删除的res', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
      }).catch(() => {})
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      return hireType[num] || '未知'
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 用户点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true

      this.curEmployeId = id
    },
    hCloseDialog() {
      this.$refs.AddEmployee.resetForm()
    },
    // 成功添加的函数
    hsuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    }
  }
}
</script>
